const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    credit_score: 100,
    categorys: [],
    username: "",
    showName: "",
    categoryVisible: false,
    category: "",
    kinds: [],
    kind: "",
    kindVisible: false,
    kindId: "",
    datetime: '',
    datetimeVisible: false,
    datetimeVisible2: false,
    count: 1,
    key: 'apply',
    list: [
      { value: 'apply', label: '物料申领' },
      { value: 'my', label: '我的申领' },
    ],
    borrow_list: [],
    isShowQrcode: false,
    text: '',
    animationData: {},
    white_list: [],
    apply_times: [],
    scheduleId: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.credit_score = app.globalData.localuserinfo.credit_score;
    this.setData({ username: app.globalData.localuserinfo.username, showName: app.globalData.localuserinfo.showName })
    var that = this;
    if (this.data.credit_score < 60) {
      return;
    }
    wx.request({
      url: app.globalData.url + '/wechat/categorys',
      method: 'get',
      header: {
        'content-type': 'application/json'
      },
      success: res => {
        const categorys = res.data.map(v => { return { "label": v, "value": v } })
        this.setData({ categorys })
        wx.request({
          url: app.globalData.url + '/wechat/apply_times',
          method: 'get',
          header: {
            'content-type': 'application/json'
          },
          success: res2 => {
            this.setData({ apply_times: res2.data });
            this.get_borrow_list()
          }
        })
      }
    })

  },

  get_borrow_list() {
    wx.request({
      url: app.globalData.url + '/wechat/borrow_list',
      method: 'post',
      data: {
        username: app.globalData.localuserinfo.username,
      },
      header: {
        'content-type': 'application/json'
      },
      success: res3 => {
        const list = res3.data;
        const borrow_list = list.map(l => { return { kind: l.list[0].kind, ...l, count: l.list[0].count } });
        this.setData({ borrow_list })
      }
    })
  },

  onCategoryPicker() {
    console.log("onCategoryPicker")
    this.setData({ categoryVisible: true })
  },

  onCategoryPickerCancel() {
    this.setData({ categoryVisible: false })
  },
  onCategoryPickerChange: function (e) {
    const category = e.detail.value[0];
    this.setData({ category });
    if (category === '个人实验箱') {
      wx.request({
        url: app.globalData.url + '/wechat/boxes?username=' + app.globalData.localuserinfo.username,
        method: 'get',
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          const list = res.data || [];
          const _kinds = list.map(l => l.kind)
          const kinds = _kinds.map(kind => { return { ...kind, "label": kind.name, "value": kind.objectId } })
          this.setData({ kinds, white_list: list, count: 1 })
        }
      })
    } else
      wx.request({
        url: app.globalData.url + '/wechat/kinds?category=' + this.data.category,
        method: 'get',
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          const _kinds = res.data || [];
          const kinds = _kinds.map(kind => { return { ...kind, "label": kind.name, "value": kind.objectId } })
          this.setData({ kinds })
        }
      })
  },

  onKindPicker() {
    this.setData({ kindVisible: true })
  },

  onKindPickerCancel() {
    this.setData({ kindVisible: false })
  },
  onKindPickerChange: function (e) {
    const kindId = e.detail.value[0];
    const kind = this.data.kinds.find(k => k.objectId === kindId)
    this.setData({ kind: kind.name, kindId });
  },

  showDatePicker() {
    this.setData({ datetimeVisible: true })
  },
  showDatePicker2() {
    this.setData({ datetimeVisible2: true })
  },

  onDateChange(e) {
    const value = e.detail.value;
    this.setData({ datetime: value })
  },

  onDateChange2(e) {
    const objectId = e.detail.value[0];
    const apply_time = this.data.apply_times.find(t => t.objectId === objectId);
    const users = apply_time.users && apply_time.users.length || 0;
    if (users >= apply_time.capacity) {
      return wx.showToast({
        title: '该时间段预约人数已满！',
        icon: 'none',
        duration: 2000
      })
    }
    this.setData({ datetime: apply_time.date + " " + apply_time.begin + "~" + apply_time.end + "  ", scheduleId: objectId })
  },
  hideDatePicker2() {
    this.setData({ datetimeVisible2: false })
  },
  hideDatePicker() {
    this.setData({ datetimeVisible: false })
  },

  bindCountInput: function (e) {
    this.setData({
      count: e.detail.value
    })
  },

  apply() {
    if (!this.data.kind) {
      return wx.showModal({
        title: '提示',
        content: '没有选择种类',
        success: (res) => {
        }
      })
    };
    if (this.data.count <= 0) {
      return wx.showModal({
        title: '提示',
        content: '请输入领取数量！',
        success: (res) => {
        }
      })
    };
    if (this.data.category === '个人实验箱' && this.data.count > 1) {
      return wx.showModal({
        title: '提示',
        content: '领取数量不能大于1',
        success: (res) => {
        }
      })
    }
    const kind = this.data.kinds.find(k => k.objectId === this.data.kindId);
    const count = kind.count - kind.used;
    if (count < this.data.count) {
      return wx.showModal({
        title: '提示',
        content: '领取数量超过库存！',
        success: (res) => {
        }
      })
    }
    if (!this.data.datetime) {
      return wx.showModal({
        title: '提示',
        content: '请选择领取时间！',
        success: (res) => {
        }
      })
    }
    app.globalData.kind = kind;
    wx.request({
      url: app.globalData.url + '/wechat/add_to_list',
      method: 'post',
      data: {
        username: app.globalData.localuserinfo.username,
        kind,
        count: this.data.count,
        time: this.data.datetime,
        scheduleId: this.data.scheduleId,
        isApply:this.data.category === '个人实验箱'?true:false
      },
      header: {
        'content-type': 'application/json'
      },
      success: res => {
        const result = res.data;
        console.log("result",result)
        if (result.status === 'fail') {
          return wx.showModal({
            title: '申领失败',
            content: result.err,
            success: (res) => {

            }
          })
        }else{
          return wx.showModal({
            title: '申领成功',
            content: '申领成功,请到我的申领下查看',
            success: (res) => {
              this.get_borrow_list()
            }
          })
        }
      }
    })
  },

  changeKey(e) {
    this.setData({ key: e.detail.value });
  },



  //显示对话框
  showQrcode: function (e) {
    const listId = e.target.id;
    const list = this.data.borrow_list.find(l => l.objectId === listId);
    if (!list.isApply) {
      return;
    }
    if (list.hasReturn) {
      return;
    }
    if (list.hasUsed) {
      wx.redirectTo({
        url: '../fault_record/fault_record?listId=' + listId,
        fail: res => {
          console.log(res);
        },
      });
      return
    }

    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      isShowQrcode: true,
      text: listId
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  closeDialog: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        isShowQrcode: false
      })
    }.bind(this), 200)
  },

  goPage(e) {
    const listId = e.target.id;
    console.log('listId', listId)
    wx.redirectTo({
      url: '../fault_record/fault_record?listId=' + listId,
      fail: res => {
        console.log(res);
      },
    });
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})